﻿namespace VK.Lib
{

	/// <summary>
	/// Represents the VK OAuth Client.
	/// </summary>
	public class VKOAuthClient
	{

		/// <summary>
		/// The VK AppId.
		/// </summary>
		private string _appId;

		/// <summary>
		/// The VK Scope.
		/// </summary>
		private string _scope;

		/// <summary>
		/// Initializes a new instance of the <see cref="VKOAuthClient"/> class.
		/// </summary>
		public VKOAuthClient()
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="VKOAuthClient"/> class.
		/// </summary>
		/// <param name="vkApplication">
		/// The VK application.
		/// </param>
		public VKOAuthClient(IVKApplication vkApplication)
		{
			if (vkApplication != null)
			{
				_appId = vkApplication.AppId;
				_scope = vkApplication.Scope;
			}
		}

		/// <summary>
		/// Gets or sets the app id.
		/// </summary>
		public virtual string AppId { get { return _appId; } set { _appId = value; } }

		/// <summary>
		/// Gets or sets the app id.
		/// </summary>
		public virtual string Scope { get { return _scope; } set { _scope = value; } }

		#region Login url helpers

		/// <summary>
		/// Get login dialog url
		/// </summary>
		/// <param name="parameters">The Dictionary.</param>
		/// <returns>The URI of login url</returns>
		public virtual System.Uri GetLoginDialogUrl(System.Collections.Generic.IDictionary<string, object> parameters)
		{
			var defaultParameters = new System.Collections.Generic.Dictionary<string, object>();

			defaultParameters["client_id"] = AppId;
			defaultParameters["scope"] = Scope;

			var mergedParameters = VKUtils.Merge(defaultParameters, parameters);

			// check if client_id is not null or empty.
			if (mergedParameters["client_id"] == null || string.IsNullOrEmpty(mergedParameters["client_id"].ToString()))
				throw new System.ArgumentException("client_id required.");

			// check if scope is not null or empty.
			if (mergedParameters["scope"] == null || string.IsNullOrEmpty(mergedParameters["scope"].ToString()))
				throw new System.ArgumentException("scope required.");

			var url = VKUtils.ToOAuthClientLoginString(mergedParameters);
			return new System.Uri(url, System.UriKind.Absolute);
		}

		/// <summary>
		/// Gets the login url.
		/// </summary>
		/// <returns>
		/// Returns the Vkontakte login url.
		/// </returns>
		public virtual System.Uri GetLoginDialogUrl()
		{
			return GetLoginDialogUrl(null);
		}

		#endregion

	}

}